import { IDownloader, IURLLister } from './interfaces';
import FS from 'fs/promises'
import Path from 'path'

export type Options = {
  url: string;
  lister: IURLLister
  downloader: IDownloader
}
export async function download(opts: Options) {
  const { url, downloader, lister } = opts;

  const { urls, name: dir } = await lister({ url })
  process.stdout.write(`dir: ${Path.join(__dirname, dir)}\n`);
  FS.mkdir(dir, { recursive: true }).catch(() => { });

  const total = urls.length

  while (urls.length) {
    const url = urls.splice(0, 1)[0]
    const idx = total - urls.length
    process.stdout.write(`[${idx}/${total}]${url}`);

    try {
      const { buffer, fileName } = await downloader({ url });
      const filePath = Path.join(dir, fileName);
      await FS.writeFile(filePath, buffer);
      process.stdout.write(' √\n');
    } catch (e) {
      process.stdout.write(' ×\n');
      console.trace(e);
      urls.push(url)
    }
  }
}
